package com.base.receiver

import com.base.callback.BleScanCallback
import android.content.BroadcastReceiver
import android.content.Intent
import android.text.TextUtils
import android.bluetooth.BluetoothDevice
import android.bluetooth.BluetoothAdapter
import android.content.Context
import com.base.event.BleEvent
import com.base.event.post.postEvent
import com.base.util.log

/**
 * 蓝牙搜索广播监听
 */
class BleScanDeviceReceiver(private val btScanCallback: BleScanCallback?) : BroadcastReceiver() {
    private val set: MutableSet<BluetoothDevice> = HashSet()
    override fun onReceive(context: Context, intent: Intent?) {
        val action = intent?.action
        if (TextUtils.isEmpty(action)) return
        when (action) {
            BluetoothDevice.ACTION_FOUND -> {
                log(TAG, "onReceive: 蓝牙搜索到设备")
                /*蓝牙类型（type）（API 18开始）
            0：Unknown
             1：传统蓝牙（Classic - BR/EDR devices）
             2：低功耗蓝牙（Low Energy - LE-only）
             3：混合模式（Dual Mode - BR/EDR/LE）*/
                val btd = intent.getParcelableExtra<BluetoothDevice>(BluetoothDevice.EXTRA_DEVICE)
                    ?: return
                set.add(btd)
                //搜索没有配对过的蓝牙设备
                btScanCallback?.onDeviceFound(btd)
            }
            BluetoothAdapter.ACTION_DISCOVERY_FINISHED -> {
                log(TAG, "onReceive: 蓝牙搜索结束")
                btScanCallback?.onScanFinished()
                postEvent(BleEvent(deviceList = set.toList()))
            }
        }
    }

    companion object {
        private const val TAG = "BleScanDeviceReceiver"
    }
}